package com.srwl.mytx.activity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ProgressBar;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.srwl.mytx.Constant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.adapter.TransferRecordAdapter;
import com.srwl.mytx.domain.CoinTransfer;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.service.TransferService;
import com.srwl.mytx.widget.NodataFooter;
import com.srwl.mytx.widget.RPTitleBar;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import me.dkzwm.widget.srl.MaterialSmoothRefreshLayout;
import me.dkzwm.widget.srl.SmoothRefreshLayout;
import me.dkzwm.widget.srl.extra.footer.MaterialFooter;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class TransferRecordActivity extends BaseActivity {
    private static final String TAG = "TransferRecordActivity";
    @BindView(R.id.refresh_layout)
    MaterialSmoothRefreshLayout refreshLayout;
    @BindView(R.id.rv_transfer_list)
    RecyclerView rv_transferList;
    @BindView(R.id.progress_bar)
    ProgressBar progressBar;
    private int page = 1;
    private boolean hasNextPage = true;
    private List<CoinTransfer> transferList = new ArrayList<>();
    private TransferRecordAdapter transferRecordAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_transfer_record);
        ButterKnife.bind(this);

        transferRecordAdapter = new TransferRecordAdapter(this, transferList);
        rv_transferList.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
        rv_transferList.setAdapter(transferRecordAdapter);
        if (isTempUser()) {
            transferRecordAdapter.showNoDataView();
        } else {
            loadData(true, false);
        }
        initRefreshLayout();
        initTitleBar();
    }

    private void initTitleBar() {
        RPTitleBar mTitleBar = findViewById(R.id.title_bar);
        mTitleBar.setSubTitleVisibility(View.GONE);
        mTitleBar.setRightImageResource(R.drawable.tx_right_menu_yellow);
        mTitleBar.setRightImageLayoutVisibility(View.VISIBLE);
        mTitleBar.setTitle("转账记录");
        mTitleBar.setLeftLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

    }

    //必须重新，不然状态栏字体是黑色，，
    protected void setStatusDark() {
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.setStatusBarColor(getResources().getColor(R.color.rp_top_red_color));
    }


    private void initRefreshLayout() {
        refreshLayout.setDisableRefresh(true);
        refreshLayout.setDisableLoadMore(false);
        refreshLayout.setEnableOverScroll(false);
        refreshLayout.setOnRefreshListener(new SmoothRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefreshing() {
                page = 1;

                if (refreshLayout.getFooterView() instanceof NodataFooter) {
                    refreshLayout.setFooterView(new MaterialFooter(TransferRecordActivity.this));
                }
                if (!isTempUser()) {
                    loadData(false, true);
                }
            }

            @Override
            public void onLoadingMore() {
                if (hasNextPage && !isTempUser()) {
                    loadData(false, false);
                } else {
                    refreshLayout.refreshComplete();
                    Log.d(TAG, "onRefreshBegin: 没有更多数据了");
                }
            }

        });
    }

    private void loadData(boolean isFirst, boolean isRefresh) {
        if (!Helper.getInstance().isNetworkConnected()) {
            if (!isFirst) refreshLayout.refreshComplete();
            showToast_v1(getString(R.string.network_anomalies));
            return;
        }
        int SIZE = 20;
        Map<String, Object> body = new HashMap<>();
        body.put("page", page);
        body.put("size", SIZE);
        if (isFirst) {
            progressBar.setVisibility(View.VISIBLE);
        }
        RetrofitManager.getInstance().createRequest(TransferService.class)
                .queryTransfer(body)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        if (isFirst) {
                            progressBar.setVisibility(View.INVISIBLE);
                        } else {
                            refreshLayout.refreshComplete();
                        }

                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            showToast(getString(R.string.system_busy));
                            transferRecordAdapter.showErrorView();
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());
                            showToast(getString(R.string.system_busy));
                            transferRecordAdapter.showErrorView();
                            return;
                        }
                        JSONObject pageInfo = (JSONObject) result.getData();
                        Log.d(TAG, "onResponse: 获取转账记录完成" + pageInfo.toJSONString());
                        hasNextPage = pageInfo.getBoolean("hasNextPage");
                        if (!hasNextPage) {
                            Log.d(TAG, "onResponse: 没有更多数据了");
                            refreshLayout.postDelayed(() -> refreshLayout.setFooterView(new NodataFooter(TransferRecordActivity.this)), 1000);
                        }

                        List<CoinTransfer> transfers = pageInfo.getJSONArray("list").toJavaList(CoinTransfer.class);
                        if (isRefresh) {
                            transferList.clear();
                        }
                        if (transfers.size() > 0) {
                            transferList.addAll(transfers);
                            transferRecordAdapter.showNormalView();
                            page++;
                        } else if (page == 1) {
                            transferRecordAdapter.showNoDataView();
                        }
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        if (isFirst) {
                            progressBar.setVisibility(View.INVISIBLE);
                        } else {
                            refreshLayout.refreshComplete();
                        }
                        Log.e(TAG, "onFailure: " + t.getMessage());
                        transferRecordAdapter.showErrorView();
                    }
                });

    }

    /**
     * 判断是否是游客
     *
     * @return
     */
    private boolean isTempUser() {

        if (UserProfileManager.getInstance().getLoginUserInfo().getType() == Constant.USER_TYPE_TEMP) {
            return true;
        }
        return false;
    }
}
